﻿#region Copyright (c) 2010 R. Uittenbosch
/*
* Copyright (C) 2010 R. Uittenbosch
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
* following conditions:
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

using System.Mobile.Mvc;
using Microsoft.Practices.Mobile.ContainerModel;
using System.Windows.Forms;
using TouchUI.System.Mobile.Mvc;
using System.Drawing;
using LinkedService.Mobile.ServiceEntities;
using LinkedService.Mobile;
using LinkedIn.Mobile.Properties;

namespace LinkedIn.Mobile
{
  public class MainFormController : Controller
  {

      public MainFormController(IView view) 
            : base(view)
        {
        
        }

        public Container Container
        {
            get;
            set;
        }

        protected override void OnInitialize(params object[] parameters)
        {
          if (parameters != null && parameters.Length > 0)
          {
            this.view.ViewData["Status"] = string.Format(Strings.NotImplemented, parameters[0]);
            // Notify the view of the changes to the status
            this.view.UpdateView("Status");
          }
          else
            this.view.UpdateView("Authentication");
        }

        private void OnPropagateEvent(object sender, PropagateEventArgs e)
        {
          NavigatorService.PropagateEvent(e);
        }    

        /// <summary>
        /// This method indicates that something has been changed in the view.
        /// </summary>
        /// <param name="key">The string key to identify what has been changed.</param>
        protected override void OnViewStateChanged(string key)
        {
          switch (key)
          {
            case "Action":
              {
                string actionToPerfom = view.ViewData["Action"].ToString();
                try
                {
                  PerformAction(actionToPerfom);
                }
                catch (LinkedInNotAuthorizedException e)
                {
                  // Set AuthenticationPending
                  ApplicationManager.Configuration.SetItem("AuthenticationPending", true);
                  this.view.UpdateView("Authentication");
                  NavigatorService.Navigator.Navigate<LoginController>(new ErrorEventArgs() { AuthenticationUrl = e.AuthorizationUri.ToString(), Message = e.Message, Exception = e });
                }
                break;
              }           
            default:
              {
                break;
              }
          }                    
        }

        private void CheckPermission()
        {
          if (ApplicationManager.Configuration.GetItem<bool>("NetworkPermission"))
            this.View.UpdateView("Permission");
          else
            NavigatorService.Navigator.Navigate<NetworkPermissionController>();
        }

        private void Authenticate()
        {
          if (ApplicationManager.Configuration.GetItem<bool>("AuthenticationPending"))
          {
            this.view.UpdateView("Authentication");
            NavigatorService.Navigator.Navigate<LoginController>(new ErrorEventArgs() { AuthenticationUrl = string.Empty, Message = "retry", Exception = new LinkedInNotAuthorizedException() });
            // Do not do anything else.
            return;
          }

          try
          {
            // Try to get the current user profile
            Person p = ApplicationManager.Service.GetCurrentUser();
            
            // In case not possible, navigate to the logincontroller
            if (!ApplicationManager.Service.Succesfull)             
              ApplicationManager.NavigateToErrorHandling();


            // Remember our own id.
            if (string.IsNullOrEmpty(ApplicationManager.Configuration.GetItem<string>("CurrentUser")))
            {
              p = ApplicationManager.Service.GetCurrentUserF();
              ApplicationManager.Configuration.SetItem<string>("CurrentUser", p.Id);
            }

            //Go to the first screen
            PerformAction(ApplicationManager.Configuration.GetItem("MainScreen", "Updates"));
          }
          catch (LinkedInNotAuthorizedException e)
          {
            // Set AuthenticationPending
            ApplicationManager.Configuration.SetItem("AuthenticationPending", true);
            this.view.UpdateView("Authentication");
            NavigatorService.Navigator.Navigate<LoginController>(new ErrorEventArgs() { AuthenticationUrl = e.AuthorizationUri.ToString(), Message = e.Message, Exception = e });
          }
        }

        private void ReAuthenticate()
        {
          NavigatorService.Navigator.Navigate<LoginController>();
        }

        private void ShowConnections()
        {
          NavigatorService.Navigator.Navigate<ConnectionsController>();
        }

        private void ShowProfile()
        {
          NavigatorService.Navigator.Navigate<ProfileController>();
        }

        private void ShowUpdates()
        {
          NavigatorService.Navigator.Navigate<UpdatesController>();
        }

        private void ChangeStatus()
        {
          NavigatorService.Navigator.Navigate<StatusController>();
        }

        private void Search()
        {
          NavigatorService.Navigator.Navigate<SearchController>();
        }

        private void Invite()
        {
          NavigatorService.Navigator.Navigate<InviteController>();
        }

        private void PerformAction( string action)
        {
          switch (action)
          {
            case "Search":
              {
                this.Search();
                break;
              }
            case "Status":
              {
                this.ChangeStatus();
                break;
              }
            case "Connections":
              {
                this.ShowConnections();
                break;
              }
            case "Profile":
              {
                this.ShowProfile();
                break;
              }
            case "Updates":
              {
                this.ShowUpdates();                
                break;
              }
            case "Authenticate":
              {
                this.Authenticate();
                break;
              }
            case "Permission":
              {
                this.CheckPermission();
                break;
              }
            case "Invite":
              {
                this.Invite();
                break;
              }
            case "ReAuthenticate":
              {
                this.ReAuthenticate();
                break;
              }
            case "" :
              break;
            default:
              {
                // Pass the status to the view
                this.view.ViewData["Status"] = string.Format(Strings.NotImplemented, action);
                // Notify the view of the changes to the status
                this.view.UpdateView("Status");
                break;
              }

          }
           
        }
  }
}
